using MediatR;
using ThreeTeams.Domain.ThreeTeams.Domain.Entities;
using WMS.Api.Application.Commands;
using WMS.Common;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers
{
    /// <summary>
    /// 删除产品命令处理程序
    /// </summary>
    public class DeleteProductCommandHandler : IRequestHandler<DeleteProductCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Product> _productRepository;

        public DeleteProductCommandHandler(IBaseRepository<Product> productRepository)
        {
            _productRepository = productRepository;
        }

        public async Task<ApiResult<int>> Handle(DeleteProductCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>("删除产品");

            try
            {
                // 检查产品是否存在
                var product = await _productRepository.GetValueByIdAsync(request.Id);
                if (product == null)
                {
                    result.code = StatusCodeEnum.DataNotExist;
                    result.msg = "产品不存在";
                    return result;
                }

                // 删除产品
                var affectedRows = await _productRepository.DelDataAsync(p => p.Id == request.Id);

                result.Success(affectedRows);
            }
            catch (Exception ex)
            {
                result.code = StatusCodeEnum.Fail;
                result.msg = $"删除产品失败：{ex.Message}";
            }

            return result;
        }
    }

    /// <summary>
    /// 批量删除产品命令处理程序
    /// </summary>
    public class BatchDeleteProductCommandHandler : IRequestHandler<BatchDeleteProductCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Product> _productRepository;

        public BatchDeleteProductCommandHandler(IBaseRepository<Product> productRepository)
        {
            _productRepository = productRepository;
        }

        public async Task<ApiResult<int>> Handle(BatchDeleteProductCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>("批量删除产品");

            try
            {
                // 删除产品
                var affectedRows = await _productRepository.DelDataAsync(p => request.Ids.Contains(p.Id));

                result.Success(affectedRows);
            }
            catch (Exception ex)
            {
                result.code = StatusCodeEnum.Fail;
                result.msg = $"批量删除产品失败：{ex.Message}";
            }

            return result;
        }
    }
} 